<template>
	<view class="container">			
		<view class="dis-flex">
			<view class="user-info">
				<view class="user-name">你好,{{userInfo?userInfo.user_info.nickname:''}}</view>
				<view class="user-role" v-if="showRole!=''">{{showRole}}</view>			
			</view>
			<view @click="navTo()">签到规则</view>
		</view>
		
		<view class="dis-two-flex">
			<view class="turn-s">
				<view class="flex1">累计出勤课节</view>
				<view>{{had}}</view>			
			</view>
			<view class="turn-s">
				<view class="flex1">累计缺勤课节</view>
				<view>{{total>=future?total-future:0}}</view>			
			</view>
		</view>
		
		<view class="dis-flex" style="flex-direction: column;">
			<view style="display: flex;width: 100%;">
				<view class="today">今日课程</view>
				<view class="course-name">
					<view v-if="course_range.length==0">无<text class="cell-icon yticon icon-xia"  style="font-size: 26rpx;color:#999999"></text></view>
					
					<uni-data-select v-else @change="changeCourse"  v-model="course_selected" :clear="false" :placeholder="_selectPlace" :localdata="course_range"></uni-data-select>
				</view>
			</view>
			
			<view v-if="course_range.length>0" style="width: 100%;">
				<view class="sign-column">
					<view class="flex1">应上课  {{start_time}}</view>
					<view class="sign-color" style="color: #0191FF;" v-if="bu_sign"  @click="signClick(1)">补签</view>
					<view class="sign-color" v-else>{{sign_str1}}</view>
				</view>
				<view class="sign-column" style="margin-top: 40rpx;">
					<view class="flex1">应下课  {{end_time}}</view>
					<view class="sign-color">{{sign_str2}}</view>
				</view>
				<view style="display: flex;justify-content: center;" v-if="can_sign1||can_sign2">
					<view class="yuan" @click="signClick(2)" :class="{'activeColor': is_entrance_range&&(can_sign1||can_sign2)}">
						<view class="sign-current">{{sign_current}}</view>
						<view class="sign-current-time">{{current_time}}</view>
					</view>
				</view>
				
				<view class="sign-status" v-if="can_sign1||can_sign2">
					<view style="display: flex;align-items: center;width:100%;justify-content: center;">
						<text v-if="is_entrance_range" class="cell-icon yticon icon-entrance"></text>
						<text v-else class="cell-icon yticon icon-entrance-no"></text>
						<view style="margin-left: 20rpx;">{{entrance_tip}} : {{sign_address}}</view>
						
					</view>
				</view>
			</view>
			<view v-else class="no-course">暂无课程</view>
	
		</view>
		
	</view>
</template>

<script>
	import { mapState } from 'vuex';  
	import Api from '@/common/api';
	export default {
		
		data() {
			return {
				_selectPlace:'请选择需要签到的课程',//无
				course_selected:0,
				// course_range:[{text:'测试',value:1},{text:'测试2',value:2}],
				course_range:[],
				start_time:'',
				end_time:'',
				sign_str1:'未签到',
				sign_str2:'未签到',
				can_sign1:false,//是否需要更新上课签到（如果已签到则不需要更新）
				can_sign2:false,//是否需要更新下课签到（如果已签到则不需要更新）
				sign_current:'上课签到',
				current_time:'',
				timer: null, // 定时器
				// sign_address:'已进入签到范围：建新北路大范甘迪风风光光',
				sign_address:'重庆市沙坪坝区梨树湾',
				entrance_tip:'未进入签到范围',
				sign_lat:'29.54909042718115',
				sign_lon:'106.43919115886092',
				sign_distence:100,
				distence:200,
				duration:10*60,//超过多久为补签
				is_entrance_range:false,//是否进入签到范围
				currentTimeSecond:0,
				currentItem:{},
				secondDay:0,//今天的最大时间戳，用于计算下课最迟签到时间
				bu_sign:false,
				section_id:0,
				sign_t:1,
				total:0,
				had:0,
				future:0
			};
		},
		
		onLoad() {
			// console.log(456)
			this.getCourseList();
			this.changeLocationReal();
			this.gateStatics()
			//写一个每秒检测脚本，如果位置没有更新则自动触发更新位置（即使位置没变）
		},
		beforeCreate(){
			
		},
		beforeDestroy(){
			uni.stopLocationUpdate();
			this.clearTimer();
		},
		onHide(){
			uni.stopLocationUpdate();
			this.clearTimer();
		},
		computed: {
			...mapState(['hasLogin','userInfo','user_role']),
			checkLoginState(){
				// console.log(123,this.hasLogin)
				if(!this.hasLogin){
					uni.redirectTo({
						url:'/pages/public/wxLogin'
					})
				}
			},
			showRole:function(){
				if(this.$store.state.user_role==0){return '';}
				if(this.$store.state.user_role==1){return '老师';}
				if(this.$store.state.user_role==2){return '学生';}
				if(this.$store.state.user_role==3){return '商家';}
			}
		},
		onShow(){
			
			this.startTimer();
			
		},
		onReady(){
			
		},
		onPageScroll(e){
			
		},
		methods: {
			navTo(){
				uni.navigateTo({
					url:'/pages/public/policy?t=sign_rule'
				})
			},
			getDate(){
			  const date = new Date();
			  // console.log(parseInt(date.getTime()/1000))
			  this.currentTimeSecond =parseInt(date.getTime()/1000);
			  // 获取时分秒，并格式化为时:分:秒的字符串
			  const hours = this.padZero(date.getHours());
			  const minutes = this.padZero(date.getMinutes());
			  const seconds = this.padZero(date.getSeconds());
			  // 更新currentTime属性
			  // 模拟距离
			  // this.distence-=20;
			  
			  // this.updateColor();
			  // this.updateShang();
			  
			  return `${hours}:${minutes}:${seconds}`;
			},
			padZero(value) {
			      return value < 10 ? `0${value}` : value;
			},
			startTimer() {
			      // 设置每秒更新一次
			      this.timer = setInterval(() => {
			        this.current_time = this.getDate();
			      }, 1000); // 1000毫秒
			    },
			clearTimer() {
			  // 清除定时器
			  if (this.timer) {
				clearInterval(this.timer);
				this.timer = null;
			  }
			},
			async gateStatics(){
				let params = {};
				let data = await Api.apiCall('get', Api.apiName.course_gate_statics, params);
				if (!data ||data.code!=0) {
					return;
				}
				this.total = data.data.total;
				this.had=data.data.had;
				this.future=data.data.future;
			},
			async getCourseList() {
				let params = {};
				let data = await Api.apiCall('get', Api.apiName.course_order_today, params);
				if (!data || data.data.length==0) {
					
					return;
				}
				
				this.course_range = data.data;
				let first;
				if(this.course_selected==0){
					 first = this.course_range[0];
				}else{
					 first = this.course_range.find(obj => obj.value == this.course_selected);
				}
				
				this.currentItem = first;
				this.course_selected=first['value'];
				this.start_time = first['begin_time'];
				this.end_time = first['end_time'];
				
				this.sign_address = first['campus_info']['address'];
				this.sign_lat = first['campus_info']['latitude'];
				this.sign_lon = first['campus_info']['longitude'];
				this.sign_distence =first['campus_info']['pouch_distance'];
				this.sign_str1 = first['sign_str1'];
				this.can_sign1=first['can_sign1'];
				this.sign_str2 = first['sign_str2'];
				this.can_sign2=first['can_sign2'];
				this.secondDay = first['second_day'];
				this.sign_current=first['can_sign1']==true?'上课签到':'下课签到';
				this.section_id=first['section_id'];
			},
			changeCourse(e){
				
				let item = this.course_range.find(obj => obj.value == e);
				this.currentItem =item;
				this.start_time = item['begin_time'];
				this.end_time = item['end_time'];
				this.sign_address = item['campus_info']['address'];
				this.sign_lat = item['campus_info']['latitude'];
				this.sign_lon = item['campus_info']['longitude'];
				this.sign_distence =item['campus_info']['pouch_distance'];
				this.sign_str1 = item['sign_str1'];
				this.can_sign1=item['can_sign1'];
				this.sign_str2 = item['sign_str2'];
				this.can_sign2=item['can_sign2'];
				this.secondDay = item['second_day']
				this.sign_current='上课签到';
				this.section_id = item['section_id'];
			},
			
			changeLocationReal(){
						
				// if(!this.hasLogin){
				// 	console.log('未登录不更新位置');
				// 	return;
				// }
				let that=this;
				uni.startLocationUpdate({
					success:res=>{
						uni.onLocationChange(function(rel){
							var str = rel.latitude+','+rel.longitude;
							// console.log('位置',rel);
							// let distence = that.getDistance(that.sign_lat, that.sign_lon, rel.latitude, rel.longitude)
							
							that.distence = that.distanceBetweenCoordinates(that.sign_lat, that.sign_lon, rel.latitude, rel.longitude)
							// that.$api.msg(`${distence}`)
							// console.log('目的地',that.sign_lat,that.sign_lon,'当前',rel.latitude,rel.longitude,'距离',distence,distence2)
							
							that.updateColor();
							that.updateShang();
						})
					},
					fail:err=>console.error('开启小程序接收位置消息失败：', err),
					complete: msg => {
						console.log('调用开启小程序接收位置消息 API 完成');
						
					}
				})
			},
			// 计算两点距离
			getDistance(lat1, lng1, lat2, lng2) {
				let EARTH_RADIUS = 6378.137;
				let radLat1 = this.rad(lat1);
				let radLat2 = this.rad(lat2);
				let a = radLat1 - radLat2;
				let b = this.rad(lng1) - this.rad(lng2);
				let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
					Math.cos(radLat1) * Math.cos(radLat2) *
					Math.pow(Math.sin(b / 2), 2)));
				s = s * EARTH_RADIUS;
				s = Math.round(s);
				
				//s = Math.round(s * 10000d) / 10000d;
				s = Math.round(s * 10000) / 10000;
				let that =this
				
				s = s * 1000; //乘以1000是换算成米
				return s;
			},
			// 弧度计算
			rad(d) {
				return d * Math.PI / 180.0;
			},
			signClick(t){
				// console.log(this.is_entrance_range,t)
				if(!this.can_sign1&&!this.can_sign2){
					return;
				}
				// if(!this.is_entrance_range){this.$api.msg(`请进入签到范围签到`);return;}
				
				let content = this.sign_t==1?'确定上课签到吗':'确定下课签到吗';
				let that = this;
				uni.showModal({
					title:'提示',
				    content: content,
				    success: async (e)=>{
				    	if(e.confirm){
				    		let params = {c_id:that.course_selected,s_id:that.section_id,t:t,st:that.sign_t,role:that.$store.state.user_role};
				    		let data = await Api.apiCall('post', Api.apiName.course_sign, params);
				    		if (!data || !data.data) {
								that.$api.msg(`${data.data.msg}`);
				    			return;
				    		}
							if(that.bu_sign&&that.sign_t==1){that.bu_sign=false;}//补签成功更新状态，否则会一直显示补签除非手动刷新
							that.$api.msg(`签到成功`);
				    		setTimeout(function(){
								that.getCourseList();
							},1500)
				    	}
				    }
				});
				
				
			},
			//更新圆圈颜色和下方签到范围文字
			updateColor(){
				if(this.distence>this.sign_distence){
					this.entrance_tip='未进入签到范围';
					this.is_entrance_range=false;
					return;
				}
				this.entrance_tip='已进入签到范围';
				this.is_entrance_range=true;
				return;
			},
			updateShang(){
				
				let remain = this.currentTimeSecond-this.currentItem.begin;
				console.log(remain,this.duration,this.can_sign1)
				if(remain>this.duration&&!this.can_sign1){
					this.sign_current='下课签到';
					this.sign_t=2
				}else{
					this.sign_t=1;
				}
				
				if(this.can_sign1&&remain>this.duration&&this.currentTimeSecond<this.currentItem.end){
					this.bu_sign=true;
					this.sign_t=1
				}else{
					this.bu_sign=false;
				}
				
			},
			toRadians(degrees) {
			  return degrees * Math.PI / 180;
			},
			distanceBetweenCoordinates(lat1, lon1, lat2, lon2) {
			  var earthRadiusKm = 6371;
			
			  var dLat = this.toRadians(lat2 - lat1);
			  var dLon = this.toRadians(lon2 - lon1);
			
			  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
			          Math.cos(this.toRadians(lat1)) * Math.cos(this.toRadians(lat2)) *
			          Math.sin(dLon/2) * Math.sin(dLon/2);
			  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
			  var distance =parseInt(earthRadiusKm * c *1000);
			
			  return distance;
			}
		},
	

	}
</script>

<style lang="scss">	

	page {
		background: #F5F5F5;
		
	}
	.dis-flex{
		background: #FFFFFF;
		display: flex;
		flex-direction: row;
		margin: 40rpx;
		border-radius: 20rpx;
		padding: 30rpx;
		font-size: 24rpx;
		align-items: center;
	}
	.dis-two-flex{
		display: flex;
		flex-direction: row;
		margin: 40rpx;
		justify-content: center;
	}
	.turn-s{
		background: #FFFFFF;
		display: flex;
		padding: 30rpx;
		width: 50%;
		border-radius: 20rpx;
		margin: 0rpx 8rpx;
		font-size: 26rpx;
	}
	.flex1{
		flex: 1;
	}
	.user-name{
		font-size: 28rpx;
		font-weight: 600;
	}
	.user-info{
		display: flex;
		flex: 1;
		align-items: center;
	}
	.user-role{
		border-radius: 16rpx;
		padding: 10rpx 20rpx;
		background: rgba(48, 133, 173, 0.15);
		margin-left: 20rpx;
	}
	.today{
		flex: 1;
		margin-left: 10rpx;
	}
	.uni-select{
		border: none !important;
		// width: 340rpx !important;
		height: 28rpx !important;
	}
	.uni-icons{
		padding-left: 10rpx;
	}
	.uni-select__input-placeholder{
		color:#999999 !important;
		text-align: right;
	}
	.uni-select__selector{
		left: 32rpx !important;
		top:calc(100% + 38rpx) !important ;
	}
	.uni-select__selector-item{
		font-size: 24rpx !important;
	}
	
	.sign-column{
		display: flex;
		width: 100%;
		padding: 24rpx;
		background: #E0EDF3;
		margin-top: 60rpx;
		border-radius: 20rpx;
	}
	.sign-color{
		color: rgba(0,0, 0, 0.4);
	}
	.yuan{
		width: 260rpx;
		height: 260rpx;
		border-radius: 50%;
		margin-top: 60rpx;
		background: #C5C6C6;
		position: relative;
	}
	.activeColor{
		background: #0191FF;
	}
	.sign-current{
		position: absolute;
		top: 34%;
		left: 72rpx;
		font-size: 30rpx;
		font-weight: 600;
		color: #FFFFFF;
	}
	.sign-current-time{
		position: absolute;
		top: 60%;
		left: 72rpx;
		font-size: 28rpx;
		color: #FFFFFF;
	}
	.sign-status{
		display: flex;
		width: 100%;
		padding: 24rpx;
		
	}
	.no-course{
		height: 700rpx;
		justify-content: center;
		align-items: center;
		display: flex;
		font-size: 16px;
		color: #999999;
	}
</style>
